package com.example.filemanager.demos.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

@Controller
public class FileController {

    static private final byte message [] = { 83, 111, 109, 101, 32,
            98, 121, 116, 101, 115, 46 };
    static public void main(String args[]) throws Exception {
        FileOutputStream fout = new FileOutputStream("d:\\test.txt");
        //新建渠道
        FileChannel fc = fout.getChannel();
        //新建buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        for (int i = 0; i < message.length; ++ i) {
            buffer.put(message[i]);
        }
        buffer.flip();
        //写入渠道
        fc.write(buffer);
        fout.close();
    }

    @GetMapping("/download/{targetFile}")
    public HttpServletResponse download(@PathVariable("targetFile") String targetFile,
                                        HttpServletResponse response) {
        
        try {
            String path = "D:\\temp1\\" + targetFile;
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }
}
